package com.wuwangfu.transfor;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author jcshen
 * @Date 2023-02-22
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: ReduceTransf
 * @Description:
 * @Version 1.0.0
 */
public class ReduceTransf {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = line.map(w -> Tuple2.of(w, 1)).returns(Types.TUPLE(Types.STRING,Types.INT));
        maped.keyBy(t -> t.f0)
                .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> v1, Tuple2<String, Integer> v2) throws Exception {

                        /**
                         * v1：第一个数据的数据或中间累加的结果
                         * v2：以后输入key相同的数据
                         * Integer acc = v1.f1;
                         * Integer in = v2.f1;
                         * Integer sum = acc + in;
                         * String word = v1.f0;
                         */
                        v1.f1 = v1.f1 + v2.f1;
                        return v1;
                    }
                }).print();


        env.execute();
    }
}
